<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">

        <el-form-item label="题目" prop="className">
          <el-input
            v-model="queryParams.questionsName"
            placeholder="请输入题目"
            clearable
            size="small"
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="专业" prop="status">
          <el-select v-model="queryParams.major" clearable filterable >
              <el-option v-for="item in majorList" :label="item.subjectName+''" placeholder="班级专业"
                  :value="item.id+''" :key="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="科目" prop="classDept">
          <el-select v-model="queryParams.subjects" clearable filterable size="small" >
              <el-option v-for="dict in subjectList" :key="dict.id" :label="dict.subjName" :value="dict.id+''" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" ref="multipleTable" :data="tableData" @select="selectFn" @select-all="selectAllFn">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="专业" align="center" prop="major" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            {{ getMajorLable(scope.row.major) }}
          </template>
        </el-table-column>
        <el-table-column label="科目" align="center" prop="subjects" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            {{ getSubjectLable(scope.row.subjects) }}
          </template>
        </el-table-column>
        <el-table-column label="试题类型" align="center" prop="questionsType" width="100" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <label v-if="scope.row.questionsType==1">单选题</label>
            <label v-if="scope.row.questionsType==2">多选题</label>
            <label v-if="scope.row.questionsType==3">判断题</label>
            <label v-if="scope.row.questionsType==4">填空题</label>
            <label v-if="scope.row.questionsType==5">问答题</label>
          </template>
        </el-table-column>
        <el-table-column label="试题题目" align="center" prop="questionsName" width="180" :show-overflow-tooltip="true" >
        </el-table-column>
        <el-table-column label="年級" align="center" prop="grade" width="160">
          <template slot-scope="scope">
            {{ selectDictLabel(classGradeList, scope.row.grade) }}
          </template>
        </el-table-column>
        <el-table-column label="分数分数" align="center" prop="sore" width="160">
        </el-table-column>


      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div style="text-align: center;">
          <el-button type="primary" @click="confirm">确 认</el-button>
          <el-button @click="close">关 闭</el-button>
      </div>
    </div>
  </template>

  <script>

  import { findBaseSpaceLocationPageList} from "@/api/baseData/siteManagement";
  import { getClassTeacherList } from "@/api/system/user";
  import { findBaseSubjectPageList} from "@/api/baseData/profession";

  import { tExamSubjectPageList} from "@/api/studentInfo/questions";
  import {subjectList} from "@/api/educational/subject.js";

const arrFindObjIndex = (arr, obj, key) => {
  let index = -1;
  arr.forEach((item, idx) => {
    if (item[key] === obj[key]) {
      index = idx;
    }
  });
  return index;
};
  export default {
    name: "questionListComponent",
    props:{
      dataList: {
        type: Array,
        default: []
      },
      showDialog: Boolean,
      multiple: Boolean
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 班主任
        userOptions: [],
        // 状态数据字典
        statusOptions: [],
        // 班级所属部门
        classDeptOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          className: undefined,
          status: undefined,
          classDept:undefined
        },
        total:0,
        subjectList:[],
        majorList:[],//专业
        termTimeList:[],
        courseTypeOptions:[],
        classOptions:[],
        classGradeList:[],
        temporaryRowList:[],
        lastingRowList:[],
        selection: [],
        tableData: [],
      };
    },
    created() {
      this.getMajortList()
      this.getList();
      this.getClassTeacherList();
      this.getSubjectList()
      this.getDicts("class_grade").then(response => {
        //年级
        this.classGradeList = response.data;
      });
      if(this.dataList && this.dataList.length>0){
        this.selection = this.dataList
      }

    },
    methods: {
      confirm(){
        this.$emit('getQuestionList',this.selection,false)
      },
      close(){
        this.$emit('closeQuestionList')
      },
      //   翻页之后调用该方法
    toggleSelection() {
      //翻页之后要勾选上一页选中的,增加延时,在列表渲染完成后选中
      const _this = this
      setTimeout(() => {
        console.log(this.selection)
        this.selection.forEach((item) => {
          if (arrFindObjIndex(this.selection, item, "id") !== -1) {
            _this.$refs.multipleTable.toggleRowSelection(item);

          }
        });
      },500)
    },
    selectAllFn(selection) {
      if (!selection.length) {
        // 全选时，选中的数据为空时，要清理掉缓存中当页的数据
        this.tableData.forEach((item) => {
          const index = arrFindObjIndex(this.selection, item, "id");
          if (index !== -1) {
            this.selection.splice(index, 1);
          }
        });
      } else {
        // 全选时，选中的数据不为空时，要在缓存中添加当页的数据
        selection.forEach((item) => {
          const index = arrFindObjIndex(this.selection, item, "id");
          if (index === -1) {
            this.selection.push(item);
          }
        });
      }
    },
    selectFn(selection, row) {
      const flag = selection.some((item) => {
        return item.id === row.id;
      });
      console.log('flag',flag)
      const index = arrFindObjIndex(this.selection, row, "id");
      console.log('index',index)
      if (!flag) {
        // selection中不包含row则是取消选中该行
        if (index !== -1) {
          this.selection.splice(index, 1);
          console.log('splice',this.selection)
        }
      } else {
        // selection中不包含row则是选中该行
        if (index === -1) {
          this.selection.push(row);
        }else{
          this.selection.splice(index, 1);
        }
      }

    },
        getClassRoom(){
            findBaseSpaceLocationPageList({pageNum:1,pageSize:1000,locationType:4}).then(response => {
                this.classRoomOptions = response.data.list;
            });
        },
      getMajortList(){
        //查询科目
        findBaseSubjectPageList({pageSize:100,pageNum:1,status:1}).then(response =>{
            this.majorList = response.data.list
        })
      },
      getSubjectList(){
            //查询专柜
        subjectList({pageSize:100,pageNum:1,status:1}).then(response =>{
            this.subjectList = response.data.list
        })
      },
      getMajorLable(val){
        for(let i=0;i<this.majorList.length;i++){
          if(this.majorList[i].id==val){
            return this.majorList[i].subjectName
          }
        }
      },
      getSubjectLable(val){
        for(let i=0;i<this.subjectList.length;i++){
          if(this.subjectList[i].id==val){
            return this.subjectList[i].subjName
          }
        }
      },
      /** 查询班级列表 */
      getList() {
        const _this = this
        this.loading = true
        tExamSubjectPageList(this.queryParams).then(response => {
            this.tableData = response.data.list;
            this.total = response.data.total;
            this.loading = false;
            // _this.toggleSelection()
            this.selection.forEach(item=>{
              this.tableData.forEach(itemTable=>{
                if(item.id==itemTable.id){
                  this.$nextTick(()=>{
                  this.$refs.multipleTable.toggleRowSelection(itemTable,true);
                })
                }
              })


            })
          }
        );
      },
      getClassTeacherList(){
        getClassTeacherList().then(response => {
          this.userOptions = response.data;
        });
      },
      // 字典设备状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 字典设备状态字典翻译
      classDeptFormat(row, column) {
        return this.selectDictLabel(this.classDeptOptions, row.classDept);
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          className: undefined,
          classTeacherId: undefined,
          status: "1",
          classDept:undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams={
          pageSize:10,
          pageNum:1,
          questionsName:null,
          questionsType:null,
          major:null,
          subjects:null,
          grade:null
        }
        this.resetForm("queryForm");
        this.handleQuery();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        console.log(selection)
        this.temporaryRowList = selection
      },
    }
  };
  </script>
